import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

public class Test {
    public List<Integer> postorderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        List<Integer> list = new LinkedList<>();
        TreeNode cur = root;
        TreeNode prev = null;
        while(cur!=null || !stack.isEmpty()) {
            while(cur!=null) {
                stack.push(cur);
                cur=cur.left;
            }
            TreeNode top = stack.peek();
            if(top.right==null || top.right==prev) {
                stack.pop();
                prev=top;
                list.add(top.val);
            } else if(top.right!=null) {
                cur=top.right;
            }
        }
        return list;
    }
}
